import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Table, message, Form, Row, Col, Button, DatePicker, Space } from 'antd'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '../../filingCaseManage/CaseManage.module.less'
const { Item } = Form
const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns () {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '操作者',
      dataIndex: 'operator',
      key: 'operator'
    },
    {
      title: '操作类型',
      dataIndex: 'action_name',
      key: 'action_name'
    },
    {
      title: '操作时间',
      dataIndex: 'create_datetime',
      key: 'create_datetime',
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD HH:mm:ss') : ''
      }
    }
  ]
  return list
}

class SystemLog extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    orderField: '',
    order: '',
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    visible: false,
    adminVisible: false,
    detailVisible: false,
    modifyData: null
  }

  formRef = React.createRef()

  // 改变状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取数据
  getTableData (form = {}) {
    const { pagination, orderField, order } = this.state
    const { current, pageSize } = pagination
    const condition = []
    const b = form.begin ? moment(`${form.begin.format('YYYY-MM-DD')} 00:00:00`) : 0
    const e = form.end ? moment(`${form.end.format('YYYY-MM-DD')} 23:59:59`) : 0
    if (b > e) {
      return message.warning('开始时间不能大于结束时间')
    }
    if (b) {
      condition.push({ k: 'create_datetime', o: '>=', v: Math.floor(b.valueOf() / 1000) })
    }
    if (e) {
      condition.push({ k: 'create_datetime', o: '<=', v: Math.floor(e.valueOf() / 1000) })
    }
    const data = {
      current,
      page_size: pageSize,
      ...form,
      condition: JSON.stringify(condition),
      plus: 1
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    this.setState({ loading: true })
    this.$get('/api/common/requestlog', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const { status } = this.props.meta || {}
    if (status) {
      this.setState({
        status
      }, () => {
        this.getTableData()
      })
    } else {
      this.getTableData()
    }
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <div className={style['title-line']} style={{ marginBottom: '24px' }}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='开始时间' name='begin'>
                    <DatePicker allowClear className={style.full} />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结束时间' name='end'>
                    <DatePicker allowClear className={style.full} />
                  </Item>
                </Col>
                <Col span={8}>
                  <Space>
                    <Button type='primary' ghost htmlType='submit'>搜索</Button>
                    <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                  </Space>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SystemLog)
